package br.com.rafsoft.mapaentrega.client;

import java.util.ArrayList;
import java.util.List;

import br.com.rafsoft.mapaentrega.shared.MapaEntregaRequestFactory;
import br.com.rafsoft.mapaentrega.shared.TaskProxy;
import br.com.rafsoft.mapaentrega.shared.TaskRequest;

import com.google.gwt.cell.client.ButtonCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
import com.google.gwt.dom.client.InputElement;
import com.google.gwt.dom.client.TextAreaElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.text.shared.SafeHtmlRenderer;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.RowStyles;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.Range;
import com.google.web.bindery.event.shared.EventBus;
import com.google.web.bindery.event.shared.SimpleEventBus;
import com.google.web.bindery.requestfactory.shared.Receiver;

public class TaskWidget extends Composite {

	public static final int OPEN = 0;
	public static final int CLOSE = 1;
	public static final int CANCEL = 2;
	public static final int ALERT = 3;

	interface TaskWidgetUiBinder extends UiBinder<Widget, TaskWidget> {
	}

	public static class TasksTable extends CellTable<TaskProxy> {

		public Column<TaskProxy, String> deleteColumn;
		public Column<TaskProxy, String> nameColumn;
		public Column<TaskProxy, String> statusColumn;
		public Column<TaskProxy, String> statusTextColumn;
		public Column<TaskProxy, String> userColumn;
		public Column<TaskProxy, String> addressColumn;

		interface TasksTableResources extends CellTable.Resources {
			@Source("TasksTable.css")
			TableStyle cellTableStyle();
		}

		interface TableStyle extends CellTable.Style {

			String columnUser();

			String columnName();

			String columnStatus();

			String columnStatusText();

			String columnTrash();

			String columnAddress();
		}

		private static TasksTableResources resources = GWT
				.create(TasksTableResources.class);

		public TasksTable() {
			super(20, resources);

			statusColumn = new Column<TaskProxy, String>(new TextCell()) {
				@Override
				public String getValue(TaskProxy object) {
					switch (object.getStatus()) {
					case OPEN:
						return "EM ABERTO";
					case CLOSE:
						return "FECHADO";
					case CANCEL:
						return "CANCELADO";
					case ALERT:
						return "ALERTA";
					default:
						return "OUTRO";
					}
				}
			};
			addColumn(statusColumn, "Status");
			addColumnStyleName(0, "columnFill");
			addColumnStyleName(0, resources.cellTableStyle().columnStatus());

			userColumn = new Column<TaskProxy, String>(new TextCell()) {
				@Override
				public String getValue(TaskProxy object) {
					return object.getUser();
				}
			};
			addColumn(userColumn, "Usuario");
			addColumnStyleName(1, "columnFill");
			addColumnStyleName(1, resources.cellTableStyle().columnUser());

			nameColumn = new Column<TaskProxy, String>(new TextCell()) {
				@Override
				public String getValue(TaskProxy object) {
					return object.getText();
				}
			};
			addColumn(nameColumn, "Descricao");
			addColumnStyleName(2, "columnFill");
			addColumnStyleName(2, resources.cellTableStyle().columnName());

			statusTextColumn = new Column<TaskProxy, String>(new TextCell()) {
				@Override
				public String getValue(TaskProxy object) {
					return object.getStatusText();
				}
			};
			addColumn(statusTextColumn, "Finalizacao");
			addColumnStyleName(3, "columnFill");
			addColumnStyleName(3, resources.cellTableStyle().columnStatusText());

			addressColumn = new Column<TaskProxy, String>(new TextCell()) {
				@Override
				public String getValue(TaskProxy object) {
					return object.getAddress();
				}
			};
			addColumn(addressColumn, "Endereco");
			addColumnStyleName(4, "columnFill");
			addColumnStyleName(4, resources.cellTableStyle().columnAddress());

			ButtonCell buttonCell = new ButtonCell(
					new SafeHtmlRenderer<String>() {
						public SafeHtml render(String object) {
							return SafeHtmlUtils
									.fromTrustedString("<img src=\"delete.png\"></img>");
						}

						public void render(String object,
								SafeHtmlBuilder builder) {
							builder.append(render(object));
						}
					});

			deleteColumn = new Column<TaskProxy, String>(buttonCell) {
				@Override
				public String getValue(TaskProxy object) {
					return "\u2717"; // Ballot "X" mark
				}
			};
			addColumn(deleteColumn, "\u2717");
			addColumnStyleName(5, resources.cellTableStyle().columnTrash());
		}
	}

	private static final int DELAY_MS = 1000;

	private static TaskWidgetUiBinder uiBinder = GWT
			.create(TaskWidgetUiBinder.class);
	private final MapaEntregaRequestFactory requestFactory = GWT
			.create(MapaEntregaRequestFactory.class);
	private final EventBus eventBus = new SimpleEventBus();

	private List<TaskProxy> tasksList;

	@UiField
	TextAreaElement textAreaText;

	@UiField
	InputElement textBoxUser;

	@UiField
	InputElement textBoxAddress;

	@UiField
	TasksTable tasksTable;

	public TaskWidget() {
		initWidget(uiBinder.createAndBindUi(this));
		requestFactory.initialize(eventBus);

		ListDataProvider<TaskProxy> listDataProvider = new ListDataProvider<TaskProxy>();
		listDataProvider.addDataDisplay(tasksTable);
		tasksList = listDataProvider.getList();

		tasksTable.setRowStyles(new RowStyles<TaskProxy>() {
			public String getStyleNames(TaskProxy row, int rowIndex) {
				Range visibleRange = tasksTable.getVisibleRange();
				int lastRow = visibleRange.getStart()
						+ visibleRange.getLength() - 1;
				if (rowIndex == tasksList.size() - 1 || rowIndex == lastRow) {
					return isDone(row) ? "task complete last"
							: "task incomplete last";
				} else {
					return isDone(row) ? "task complete" : "task incomplete";
				}
			}
		});

		/*
		 * tasksTable.dateColumn .setFieldUpdater(new FieldUpdater<TaskProxy,
		 * Date>() { public void update(int index, TaskProxy task, Date value) {
		 * TaskRequest request = requestFactory.taskRequest(); TaskProxy
		 * updatedTask = request.edit(task); // updatedTask.setDueDate(value);
		 * request.updateTask(updatedTask).fire(); } });
		 */

		tasksTable.deleteColumn
				.setFieldUpdater(new FieldUpdater<TaskProxy, String>() {
					public void update(int index, TaskProxy task, String value) {
						TaskRequest request = requestFactory.taskRequest();
						request.deleteTask(task).fire();
						tasksList.remove(task);
					}
				});

		Scheduler.get().scheduleFixedDelay(new RepeatingCommand() {
			public boolean execute() {
				retrieveTasks();
				return true;
			}
		}, DELAY_MS);

	}

	boolean isDone(TaskProxy t) {
		return t != null;
	}

	private void retrieveTasks() {
		requestFactory.taskRequest().queryTasks()
				.fire(new Receiver<List<TaskProxy>>() {
					@Override
					public void onSuccess(List<TaskProxy> tasks) {
						if (tasks.size() > 0) {
							// signin.setText("Logged in as " +
							// tasks.get(0).getEmailAddress());
						}

						// sort first
						ArrayList<TaskProxy> sortedTasks = new ArrayList<TaskProxy>(
								tasks);
						// Collections.sort(sortedTasks, TASK_COMPARATOR);

						tasksList.clear();
						for (TaskProxy task : sortedTasks) {
							tasksList.add(task);
						}
					}
				});
	}

	@UiHandler("createUserButton")
	void onCreateUserButtonClick(ClickEvent event) {
		TaskRequest request = requestFactory.taskRequest();
		TaskProxy task = request.create(TaskProxy.class);
		task.setUser(textBoxUser.getValue());
		task.setAddress(textBoxAddress.getValue());
		task.setText(textAreaText.getValue());
		// request.updateTask(task).fire();

		request.updateTask(task).fire(new Receiver<TaskProxy>() {

			@Override
			public void onSuccess(TaskProxy task) {
				Window.alert("CREATE SUCCESS: " + task.getId());
			}
		});
	}
}
